/**
 * 
 */
package com.app.framework.result;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.app.framework.exception.ClientException;

/**
 * @author lisong
 * @version 2013-3-1 下午2:56:48
 */
public class RequestResult<T> implements Result {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3751859673883680034L;

	private String message;
	
	private int code = 200;
	
	private T data;
	
	public RequestResult(int code,T data,String message) {
		this.code = code;
		this.data = data;
		this.message = message;
	}
	
	public RequestResult(T data) {
		this.data = data;
	}
	/**
	 * 成功执行请求
	 * @param data
	 * @return
	 */
	public static <T> RequestResult<T> success(T data) {
		return new RequestResult<T>(data);
	}

	/**
	 * 请求执行失败
	 * @param data
	 * @param message
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static RequestResult fail(int code,String message) {
		return new RequestResult(code,null,message);
	}
	
	/**
	 * 请求执行失败
	 * @param data
	 * @param message
	 * @return
	 */
	public static <T> RequestResult<T> fail(int code,T data,String message) {
		return new RequestResult<T>(code,data,message);
	}
	
	/**
	 * 成功执行请求
	 * @param data
	 * @param message
	 * @return
	 */
	public static <T> RequestResult<T> success(T data,String message) {
		return new RequestResult<T>(200,data,message);
	}
	
	/**
	 * 由客户端引起的错误
	 * @param message
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static RequestResult clientError(String message) {
		return new RequestResult(400,null,message);
	}
	/**
	 * 由客户端引起的错误
	 * @param code
	 * @param data
	 * @param message
	 * @return
	 */
	public static <T> RequestResult<T> clientError(int code,T data,String message) {
		return new RequestResult<T>(code,data,message);
	}
	/**
	 * 由客户端引起的错误
	 * @param code
	 * @param message
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static RequestResult clientError(int code,String message) {
		return new RequestResult(code,null,message);
	}
	/**
	 * 服务器未知异常
	 * @param data
	 * @param e
	 * @return
	 */
	public static <T> RequestResult<T> serverException(T data,Throwable e) {
		int code = 500;
		if(e instanceof ClientException) {
			ClientException ce = (ClientException)e;
			code = ce.getCode();
		}
		return new RequestResult<T>(code,data,e.getMessage());
	}
	
	@SuppressWarnings("rawtypes")
	public static RequestResult serverException(Throwable e) {
		
		return serverException(null, e);
	}
	
	@Override
	public Serializable asResult() {
		Map<String,Object> parameters = new HashMap<String,Object>();
		parameters.put("code", code);
		parameters.put("message", message);
		if(data != null && Result.class.isAssignableFrom(data.getClass())) {
			parameters.put("data", ((Result)data).asResult());
		}
		else {
			parameters.put("data", data);
		}
		return (Serializable) parameters;
	}

	public T getData() {
		return data;
	}

}
